package com.xxl.job.executor.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.executor.common.util.*;
import com.xxl.job.executor.common.util.http.HttpsInitManager;
import com.xxl.job.executor.common.util.http.HttpsUtilWithPool;
import com.xxl.job.executor.pojo.MsgReceiveEntity;
import com.xxl.job.executor.pojo.TbMsgSendLog;
import com.xxl.job.executor.service.IMonitorInfoReqUrlService;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

@Service("monitorInfoReqUrlService")
public class MonitorInfoReqUrlService implements IMonitorInfoReqUrlService {
    Connection connPre = null;

    @Resource(name = "uploadFileHttpInitManager")
    HttpsInitManager uploadFileHttpInitManager;

    @Override
    public void transfer() throws Exception {
        XxlJobLogger.log("=====开始执行业务操作===");

        try {
            DataSource dataSourcePre = SpringContextHolder.getBean("dataSourcePre");
            connPre = DataSourceUtils.getConnection(dataSourcePre);
            connPre.setAutoCommit(false);

            ConfigProperties configProperties = SpringContextHolder.getBean("configProperties");
            String reqType = configProperties.getQfReqType();
//            String url = "http://10.14.11.100:9098";
            String url = configProperties.getQfUrl();
            String authCode = configProperties.getQfAuthCode();
            MsgReceiveEntity msgReceiveEntity = new MsgReceiveEntity();
            msgReceiveEntity.setDomain2(configProperties.getQfInterface());//url
            msgReceiveEntity.setCommand(reqType);
            //arraymsg 0-单对象消息  1-json数组数据对象消息 2-文件流转base64

            DateTime date = new DateTime();
//            String datePart = new StringBuffer().append(date.getYear()).append(File.separator).append(date.getMonthOfYear()).append(File.separator).append(date.getDayOfMonth()).append(File.separator).append(date.getHourOfDay()).append(File.separator).append(date.getMinuteOfHour()).append(File.separator).toString();

            String fileTime = String.format("%d%02d%02d%02d%02d%02d%03d",date.getYear(),date.getMonthOfYear(),date.getDayOfMonth(),date.getHourOfDay(),date.getMinuteOfHour(),date.getSecondOfMinute(),date.getMillisOfSecond());

            String reqDay = String.format("%d-%02d-%02d",date.getYear(),date.getMonthOfYear(),date.getDayOfMonth());

            String messageFileBasePath = configProperties.getQfFilePath();
            String jsonFileNoSuffix = reqType+"_SEND_000000_"+fileTime;
            String zipFilePath = "";
            //对jsonContent进行转换
            JSONObject obj = new JSONObject();
            obj.put("dataList", JSONArray.parseArray("[{\"day\": \""+reqDay+"\"}]"));
            obj.put("packagename", fileTime);

            byte[] body = obj.toJSONString().getBytes("UTF-8");

//            XxlJobLogger.log("[普通]datePart:" + datePart);
            String filenameNoSuffix = new StringBuffer(messageFileBasePath).append(jsonFileNoSuffix).toString();//.append(datePart)
//            XxlJobLogger.log("[普通]filenameNoSuffix:" + filenameNoSuffix);
            String jsonFileName = jsonFileNoSuffix + ".json";
//            XxlJobLogger.log("[普通]jsonFileName:" + jsonFileName);
            zipFilePath = filenameNoSuffix + ".zip";
//            XxlJobLogger.log("[普通]zipFilePath:" + zipFilePath);
            Map<String, byte[]> datas = new HashMap<String, byte[]>();
            datas.put(jsonFileName, body);
            File zipFile = new File(zipFilePath);
            if (!zipFile.getParentFile().exists()) {
                zipFile.getParentFile().mkdirs();
            }
            OutputStream output = new FileOutputStream(zipFile);
            XxlJobLogger.log("[普通]生成请求文件名:" + jsonFileNoSuffix + ".zip");
            FileUtil.zipStringToOutputStream(datas, output, "UTF-8");

            String md5 = DigestUtils.md5Hex(new FileInputStream(zipFile));
            msgReceiveEntity.setMd5(md5);
            msgReceiveEntity.setMsgfilepath(zipFilePath);

//            XxlJobLogger.log("[普通]url:" + url+msgReceiveEntity.getDomain2());

            //获取文件只考虑共享存储或者分布式文件系统，不再考虑集群本地文件系统
            File msgBodyFile = new File(msgReceiveEntity.getMsgfilepath());
            TbMsgSendLog tbMsgSendLog = HttpsUtilWithPool.httpsPostFileBinary(url+msgReceiveEntity.getDomain2(),
                    msgReceiveEntity.getMd5(), "true" , authCode, msgBodyFile, uploadFileHttpInitManager);
            tbMsgSendLog.setErrorsendintf(msgReceiveEntity.getCommand());
            tbMsgSendLog.setSendFilePath(msgReceiveEntity.getMsgfilepath());

            if (Constants.DealException.HTTPSEND_SUCCESS.getValue().intValue() == tbMsgSendLog.getSendResultCode()
                    && "000".equals(tbMsgSendLog.getResponseEntity().getCode()) ) { //http推送返回成功
                String info = tbMsgSendLog.getResponseEntity().getInfo();
                XxlJobLogger.log("[普通]http推送返回成功:"+info);

                String sql = "";
                Integer count = 0;
                Integer countInsert = 0;
                Integer countUpdate = 0;
                JSONArray dataArray = JSONArray.parseArray(info);
                for(int i=0,j=dataArray.size(); i<j; ++i) {
                    JSONObject jobj = dataArray.getJSONObject(i);
                    if (jobj.get("tradeDate") == null) {
                        continue;
                    }
                    String tradeDate = jobj.get("tradeDate").toString();
                    if (tradeDate.length() == 8) {
                        tradeDate = tradeDate.substring(0,4)+"-"+tradeDate.substring(4,6)+"-"+tradeDate.substring(6,8);
                    }
                    else {
                        continue;
                    }

                    sql = "select count(1) NUMCOUNTS from TB_CHARGE_MONITOR_INTF_RECV where TRADEDATE='"+tradeDate+"'";
                    BigDecimal cnt = DBUtils.getTableCounts(connPre, sql);
                    if (cnt.equals(new BigDecimal(0))) {
                        sql = "insert into TB_CHARGE_MONITOR_INTF_RECV(TRADEDATE,BATCHNO,DIFFETCOUTRECV,DIFFETCOUTUPLOAD,DIFFETCOUTACCOUNT," +
                                "DIFFETCOUTSPLIT,LOCALETCOUTRECV,LOCALETCOUTUPLOAD,LOCALETCOUTACCOUNT," +
                                "LOCALETCOUTSPLIT,DIFFMTCOUTRECV,DIFFMTCOUTUPLOAD,DIFFMTCOUTSPLIT," +
                                "LOCALMTCOUTRECV,LOCALMTCOUTSPLIT,ETCINRECV,MTCINRECV," +
                                "GRANTRYPASSGEN,GRANTRYPASSUPLOAD,GRANTRYPASSMERGE,GRANTRYINETCRECV," +
                                "GRANTRYINCPCRECV,GRANTRYOUTETCRECV,GRANTRYOUTCPCRECV,GRANTRYETCRECV," +
                                "GRANTRYCPCRECV,GRANTRYPASSIDNUM,INSERT_TIME,UPDATE_TIME) " +
                              "values ('"+tradeDate+"','"+fileTime+"',"+nvl(jobj.get("diffEtcOutRecv"))+","+nvl(jobj.get("diffEtcOutUpload"))+","+nvl(jobj.get("diffEtcOutAccount"))+
                                ","+nvl(jobj.get("diffEtcOutSplit"))+","+nvl(jobj.get("localEtcOutRecv"))+","+nvl(jobj.get("localEtcOutUpload"))+","+nvl(jobj.get("localEtcOutAccount"))+
                                ","+nvl(jobj.get("localEtcOutSplit"))+","+nvl(jobj.get("diffMtcOutRecv"))+","+nvl(jobj.get("diffMtcOutUpload"))+","+nvl(jobj.get("diffMtcOutSplit"))+
                                ","+nvl(jobj.get("localMtcOutRecv"))+","+nvl(jobj.get("localMtcOutSplit"))+","+nvl(jobj.get("etcInRecv"))+","+nvl(jobj.get("mtcInRecv"))+
                                ","+nvl(jobj.get("grantryPassGen"))+","+nvl(jobj.get("grantryPassUpload"))+","+nvl(jobj.get("grantryPassMerge"))+","+nvl(jobj.get("grantryInEtcRecv"))+
                                ","+nvl(jobj.get("grantryInCpcRecv"))+","+nvl(jobj.get("grantryOutEtcRecv"))+","+nvl(jobj.get("grantryOutCpcRecv"))+","+nvl(jobj.get("grantryEtcRecv"))+
                                ","+nvl(jobj.get("grantryCpcRecv"))+","+nvl(jobj.get("grantryPassIdNum"))+",sysdate,sysdate)";
                        count = DBUtils.execute(connPre, sql);
                        countInsert += count;
                    }
                    else {
                        sql = "update TB_CHARGE_MONITOR_INTF_RECV set " +
                                " BATCHNO='"+fileTime+"',DIFFETCOUTRECV="+nvl(jobj.get("diffEtcOutRecv"))+",DIFFETCOUTUPLOAD="+nvl(jobj.get("diffEtcOutUpload"))+",DIFFETCOUTACCOUNT="+nvl(jobj.get("diffEtcOutAccount"))+
                                ",DIFFETCOUTSPLIT="+nvl(jobj.get("diffEtcOutSplit"))+",LOCALETCOUTRECV="+nvl(jobj.get("localEtcOutRecv"))+",LOCALETCOUTUPLOAD="+nvl(jobj.get("localEtcOutUpload"))+",LOCALETCOUTACCOUNT="+nvl(jobj.get("localEtcOutAccount"))+
                                ",LOCALETCOUTSPLIT="+nvl(jobj.get("localEtcOutSplit"))+",DIFFMTCOUTRECV="+nvl(jobj.get("diffMtcOutRecv"))+",DIFFMTCOUTUPLOAD="+nvl(jobj.get("diffMtcOutUpload"))+",DIFFMTCOUTSPLIT="+nvl(jobj.get("diffMtcOutSplit"))+
                                ",LOCALMTCOUTRECV="+nvl(jobj.get("localMtcOutRecv"))+",LOCALMTCOUTSPLIT="+nvl(jobj.get("localMtcOutSplit"))+",ETCINRECV="+nvl(jobj.get("etcInRecv"))+",MTCINRECV="+nvl(jobj.get("mtcInRecv"))+
                                ",GRANTRYPASSGEN="+nvl(jobj.get("grantryPassGen"))+",GRANTRYPASSUPLOAD="+nvl(jobj.get("grantryPassUpload"))+",GRANTRYPASSMERGE="+nvl(jobj.get("grantryPassMerge"))+",GRANTRYINETCRECV="+nvl(jobj.get("grantryInEtcRecv"))+
                                ",GRANTRYINCPCRECV="+nvl(jobj.get("grantryInCpcRecv"))+",GRANTRYOUTETCRECV="+nvl(jobj.get("grantryOutEtcRecv"))+",GRANTRYOUTCPCRECV="+nvl(jobj.get("grantryOutCpcRecv"))+",GRANTRYETCRECV="+nvl(jobj.get("grantryEtcRecv"))+
                                ",GRANTRYCPCRECV="+nvl(jobj.get("grantryCpcRecv"))+",GRANTRYPASSIDNUM="+nvl(jobj.get("grantryPassIdNum"))+",UPDATE_TIME=sysdate " +
                                "where TRADEDATE='"+tradeDate+"'";
                        count = DBUtils.execute(connPre, sql);
                        countUpdate += count;
                    }
                }
                XxlJobLogger.log("[普通]此次请求插入:"+countInsert+"(条),更新:"+countUpdate+"(条)");

            }
            else {
                if (tbMsgSendLog.getResponseEntity() == null) {
                    XxlJobLogger.log("[普通]http推送返回失败:超时,"+tbMsgSendLog.getSendResultCode());
                }
                else {
                    XxlJobLogger.log("[普通]http推送返回失败:"+tbMsgSendLog.getResponseEntity().getFailInfos());
                }
            }

            connPre.commit();

            XxlJobLogger.log("=====完成执行业务操作===");
        }catch(Exception e){
            if (connPre != null) {
                try {
                    connPre.rollback();
                    XxlJobLogger.log("回滚成功.");
                }catch (Exception e1){
                    e1.printStackTrace();
                }
            }
            XxlJobLogger.log("抛出异常："+e.getMessage());
            throw e;
        }finally{
            if (connPre != null) {
                try {
                    connPre.setAutoCommit(true);
                    connPre.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    private String nvl(Object obj) {
        if (obj != null) {
            return obj.toString();
        }
        return "null";
    }

    public static void main(String[] args) {
        String tradeDate = "20200522";
        tradeDate = tradeDate.substring(0,4)+"-"+tradeDate.substring(4,6)+"-"+tradeDate.substring(6,8);
        String a = tradeDate;
//        try {
//            String json = "[{\"tradeDate\":20200516,\"diffEtcOutRecv\":20000,\"diffEtcOutUpload\":30000,\"diffEtcOutAccount\":10000,\"diffEtcOutSplit\":30000,\"localEtcOutRecv\":5000,\"localEtcOutUpload\":20000,\"localEtcOutAccount\":33000,\"localEtcOutSplit\":43200,\"diffMtcOutRecv\":34100,\"diffMtcOutUpload\":234200,\"diffMtcOutSplit\":23000,\"localMtcOutRecv\":54200,\"localMtcOutSplit\":236000,\"etcInRecv\":64700,\"mtcInRecv\":45260,\"grantryPassGen\":367400,\"grantryPassUpload\":534235,\"grantryPassMerge\":345234,\"grantryInEtcRecv\":764567,\"grantryInCpcRecv\":345234,\"grantryOutEtcRecv\":34526,\"grantryOutCpcRecv\":36352,\"grantryEtcRecv\":45467,\"grantryCpcRecv\":345325,\"grantryPassIdNum\":345345,\"createTime\":\"May 16, 2020 12:12:00 AM\",\"updateTime\":null},{\"tradeDate\":20200517,\"diffEtcOutRecv\":20890,\"diffEtcOutUpload\":30056,\"diffEtcOutAccount\":10785,\"diffEtcOutSplit\":36786,\"localEtcOutRecv\":5786,\"localEtcOutUpload\":25643,\"localEtcOutAccount\":37842,\"localEtcOutSplit\":43246,\"diffMtcOutRecv\":34756,\"diffMtcOutUpload\":234265,\"diffMtcOutSplit\":23243,\"localMtcOutRecv\":54223,\"localMtcOutSplit\":236563,\"etcInRecv\":64756,\"mtcInRecv\":45260,\"grantryPassGen\":367403,\"grantryPassUpload\":567846,\"grantryPassMerge\":347894,\"grantryInEtcRecv\":768452,\"grantryInCpcRecv\":345254,\"grantryOutEtcRecv\":34653,\"grantryOutCpcRecv\":36352,\"grantryEtcRecv\":45467,\"grantryCpcRecv\":345325,\"grantryPassIdNum\":345345,\"createTime\":\"May 17, 2020 12:02:03 AM\",\"updateTime\":null},{\"tradeDate\":20200518,\"diffEtcOutRecv\":28000,\"diffEtcOutUpload\":35600,\"diffEtcOutAccount\":106785,\"diffEtcOutSplit\":34673,\"localEtcOutRecv\":5097,\"localEtcOutUpload\":276896,\"localEtcOutAccount\":36785,\"localEtcOutSplit\":43223,\"diffMtcOutRecv\":34134,\"diffMtcOutUpload\":234244,\"diffMtcOutSplit\":23876,\"localMtcOutRecv\":54268,\"localMtcOutSplit\":236657,\"etcInRecv\":64723,\"mtcInRecv\":45260,\"grantryPassGen\":367413,\"grantryPassUpload\":534573,\"grantryPassMerge\":346785,\"grantryInEtcRecv\":767843,\"grantryInCpcRecv\":345632,\"grantryOutEtcRecv\":34756,\"grantryOutCpcRecv\":36352,\"grantryEtcRecv\":45467,\"grantryCpcRecv\":345325,\"grantryPassIdNum\":345345,\"createTime\":\"May 18, 2020 11:00:00 AM\",\"updateTime\":null},{\"tradeDate\":20200519,\"diffEtcOutRecv\":29000,\"diffEtcOutUpload\":30787,\"diffEtcOutAccount\":100678,\"diffEtcOutSplit\":30678,\"localEtcOutRecv\":5456,\"localEtcOutUpload\":26767,\"localEtcOutAccount\":38965,\"localEtcOutSplit\":43457,\"diffMtcOutRecv\":34156,\"diffMtcOutUpload\":234277,\"diffMtcOutSplit\":23932,\"localMtcOutRecv\":54264,\"localMtcOutSplit\":236673,\"etcInRecv\":64778,\"mtcInRecv\":45260,\"grantryPassGen\":367445,\"grantryPassUpload\":539076,\"grantryPassMerge\":342456,\"grantryInEtcRecv\":765675,\"grantryInCpcRecv\":345674,\"grantryOutEtcRecv\":34526,\"grantryOutCpcRecv\":36352,\"grantryEtcRecv\":45467,\"grantryCpcRecv\":345325,\"grantryPassIdNum\":345345,\"createTime\":\"May 19, 2020 12:00:57 AM\",\"updateTime\":null}]";
//            JSONArray dataArray = JSONArray.parseArray(json);
//
//            JSONObject jobj = dataArray.getJSONObject(0);
//            String date = jobj.get("tradeDate").toString();
//            String xx = jobj.get("xxx")==null?"null":jobj.get("xxx").toString();
//            int a = 1;
//            int b = a;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}
